package com.ycx.ycxmybatismanagement.aop;

import com.ycx.ycxmybatismanagement.dto.LoginDTO;
import com.ycx.ycxmybatismanagement.entity.EmpLoginLog;
import com.ycx.ycxmybatismanagement.mapper.LoginLogMapper;
import com.ycx.ycxmybatismanagement.pojo.Result;
import com.ycx.ycxmybatismanagement.vo.LoginResultVo;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class LoginAspect {
    @Autowired
    private LoginLogMapper loginLogMapper;
    @Around("@annotation(loginLog)")
    public Object loginAspect(ProceedingJoinPoint pjp,LoginLog loginLog) throws Throwable {


        LoginDTO arg = (LoginDTO) pjp.getArgs()[0];
        String username = arg.getUsername();
        String password = arg.getPassword();



        long start = System.currentTimeMillis();

        Result result = null;//通过

        //登录不上
        try {
            result = (Result)pjp.proceed();
        } finally {
            if (result==(null)){
                long errorTime = System.currentTimeMillis()-start;
                EmpLoginLog empLoginLog = EmpLoginLog.builder()
                        .username(username)
                        .password(password)
                        .loginTime(LocalDateTime.now())
                        .isSuccess((short)0)
                        .jwt("")
                        .costTime(errorTime)
                        .build();

                loginLogMapper.addLoginLog(empLoginLog);
            }
        }
        //登录上
        long end =System.currentTimeMillis();
        long costTime = (end - start);

        Integer code = result.getCode();//状态

        LoginResultVo loginResult = (LoginResultVo) result.getData();
        String token = loginResult.getToken();


        EmpLoginLog empLoginLog = EmpLoginLog.builder()
                .username(username)
                .password(password)
                .loginTime(LocalDateTime.now())
                .isSuccess(Short.parseShort(code.toString()))
                .jwt(token)
                .costTime(costTime)
                .build();
        loginLogMapper.addLoginLog(empLoginLog);

        return result;
    }

}
